package org.aeon.fasttasks.core.recorder;

import org.aeon.fasttasks.core.util.CsvUtils;
import org.apache.commons.csv.CSVPrinter;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * @author aeon
 * @createTime 2025/08/07  11:38
 * @description
 */
public abstract class AbstractCsvRecorder implements Recorder {

    protected final String filePath;

    protected final Path path;

    protected final List<String> headers;

    protected final boolean recordingTime;

    protected boolean isInitialized = false;

    public AbstractCsvRecorder(Path path, List<String> headers,
                               boolean recordingTime) {
        this.path = path;
        this.filePath = path.toString();
        this.headers = headers;
        this.recordingTime = recordingTime;
    }

    public AbstractCsvRecorder(String filePath, List<String> headers,
                               boolean recordingTime) {
        this.filePath = filePath;
        this.path = Paths.get(filePath);
        this.headers = headers;
        this.recordingTime = recordingTime;
    }

    /**
     * 处理文件头
     *
     * @param csvPrinter
     * @throws IOException
     */
    protected void handleHeader(CSVPrinter csvPrinter) throws IOException {

        if (!isInitialized) {
            if (CsvUtils.isFileEmpty(filePath) && headers != null && !headers.isEmpty()) {
                List<String> headersToWrite = new ArrayList<>(headers);
                if (recordingTime) {
                    headersToWrite.add("记录时间");
                }
                CsvUtils.writeHeaders(csvPrinter, headersToWrite);
            }
            isInitialized = true;
        }
    }
}
